package com.atguigu.gmall.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * title:
 * author: Gyh
 * date:2023-05-04 19:54
 * Description:
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    //登录才可以访问的静态页面地址
    @Value("${authUrls.url}")
    private List<String> authUrl;

    /**
     * 统一验证用户身份的请求
     * @param exchange 交换器对象获取请求和响应对象
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //对于静态资源直接放行
            //获取请求的地址
        String urlPath = request.getURI().getPath();
            //采用地址的匹配器进行判断
        if (antPathMatcher.match("**/js/**",urlPath) ||
                antPathMatcher.match("**/img/**",urlPath) ||
                antPathMatcher.match("**/css/**",urlPath)){
            return chain.filter(exchange);
        }

        //对于请求地址中包含"inner",说明是服务内部调用,无论是否登录,禁止直接通过网关访问
        if (antPathMatcher.match("/**/inner/**",urlPath)){
            return outError(response,ResultCodeEnum.ILLEGAL_REQUEST);
        }

        //尝试从redis中获取用户信息
        String userId = this.getUserId(request);
        if (StringUtils.isBlank(userId)){
            //对于ajax请求中包含"auth"只有登录后才可以访问,如果用户没有登录则返回401
            if (antPathMatcher.match("/**/auth/**",urlPath)){
                return outError(response,ResultCodeEnum.LOGIN_AUTH);
            }
            //对于前段部分页面(我的订单,我的购物车等)访问,只有登录后才可以访问,引导用户登录
            for (String url : authUrl) {
                if (antPathMatcher.match("/" + url,urlPath)){
                    //设置响应状态码
                    response.setStatusCode(HttpStatus.SEE_OTHER);
                    //设置重定向的地址
                    response.getHeaders().set(HttpHeaders.LOCATION,"http://passport.gmall.com/login.html?originUrl="+request.getPath());
                    return response.setComplete();
                }
            }
        }

        //动态路由同时获取到用户id设置到请求头中,将用户id透传到目标微服务中
        if (StringUtils.isNotBlank(userId)){
            request.mutate().header("userId",userId);
        }

        //将获取到临时用户ID设置到请求头
        String userTempId = getUserTempId(request);
        if (StringUtils.isNotBlank(userTempId)){
            request.mutate().header("userTempId",userTempId);
        }
        return chain.filter(exchange);
    }

    /**
     * 多个过滤器的执行顺序,值越小,优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }

    /**
     * 获取当前用户ID
     *  前端提交的ajax请求会将token放在请求头中提交
     *  浏览器地址栏同步请求会将token放在cookie中提交
     * @return
     */
    private String getUserId(ServerHttpRequest request){
        //尝试从请求头或者cookie中获取token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            HttpCookie cookie = request.getCookies().getFirst("token");
            if (cookie!=null){
                token = cookie.getValue();
            }
        }
        if (StringUtils.isBlank(token)){
            return null;
        }
        //从redis中获取用户信息
        String tokenKey = "user:" + token;
        JSONObject userJSONObject = (JSONObject) redisTemplate.opsForValue().get(tokenKey);
        if (userJSONObject != null){
            return userJSONObject.get("id").toString();
        }
        return null;
    }

    /**
     * 用来给前端响应错误提示信息
     *
     * @param response
     * @param resultCodeEnum
     * @return
     */
    private Mono<Void> outError(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        //1.准备响应结果对象,转为JSON对象
        Result<Object> result = Result.build(null, resultCodeEnum);
        String resultString = JSON.toJSONString(result);

        //2.响应结果给客户端
        //2.1 设置http状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //2.2 通过响应头设置响应数据格式-json
        response.getHeaders().add("content-type", "application/json;charset=utf-8");
        DataBuffer wrap = response.bufferFactory().wrap(resultString.getBytes());
        //2.3 网关结束响应-不再路由转发
        //return response.setComplete();
        //2.4 网关将响应数据返回给客户端
        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 尝试获取临时用户ID
     * @param request
     * @return
     */
    private String getUserTempId(ServerHttpRequest request){
        String userTempId = "";
        //尝试从cookie中获取
        List<HttpCookie> cookieList = request.getCookies().get("userTempId");
        if (!CollectionUtils.isEmpty(cookieList)){
            userTempId = cookieList.get(0).getValue();
            return userTempId;
        }
        //尝试从请求头中获取
        userTempId = request.getHeaders().getFirst("userTempId");
        if (StringUtils.isNotBlank(userTempId)){
            return userTempId;
        }
        return userTempId;
    }
}
